import 'package:get/get.dart';

import '../../../core/network/api_provider.dart';
import '../../../core/base/base_provider.dart';
import '../../../core/network/api_endpoints.dart';
import '../models/response/api_response.dart';
import '../models/device_model.dart';
import '../../constants/enums/device_type.dart';
import '../models/response/base_response.dart';

/// 设备提供者
/// 负责处理设备相关的API请求
class DeviceProvider extends BaseProvider {
  final ApiProvider _apiProvider = Get.find<ApiProvider>();
  
  /// 获取设备列表
  /// [page] 页码，从1开始
  /// [limit] 每页数量
  /// [search] 搜索关键字
  /// [sort] 排序字段
  /// [order] 排序方式（asc或desc）
  /// [type] 设备类型筛选
  /// [status] 设备状态筛选
  Future<ApiResponse<List<DeviceModel>>> getDevices({
    int page = 1,
    int limit = 10,
    String? search,
    String? sort,
    String? order,
    DeviceType? type,
    String? status,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'page': page,
        'limit': limit,
      };

      if (search != null && search.isNotEmpty) {
        params['search'] = search;
      }

      if (sort != null && sort.isNotEmpty) {
        params['sort'] = sort;
      }

      if (order != null && order.isNotEmpty) {
        params['order'] = order;
      }

      if (type != null) {
        params['type'] = type.code;
      }

      if (status != null && status.isNotEmpty) {
        params['status'] = status;
      }

      final response = await _apiProvider.get(
        ApiEndpoints.devices,
        params: params,
      );

      if (response.isOk) {
        final List<dynamic> data = response.body['data'] as List<dynamic>;
        final List<DeviceModel> devices = data
            .map((item) => DeviceModel.fromJson(item as Map<String, dynamic>))
            .toList();

        return ApiResponse<List<DeviceModel>>(
          statusCode: response.statusCode ?? 200,
          data: devices,
          message: response.body['message'] as String? ?? '获取设备列表成功',
          success: true,
          meta: response.body['meta'] as Map<String, dynamic>?,
        );
      } else {
        return ApiResponse<List<DeviceModel>>(
          statusCode: response.statusCode ?? 500,
          data: [],
          message: response.body['message'] as String? ?? '获取设备列表失败',
          success: false,
        );
      }
    } catch (e) {
      return ApiResponse<List<DeviceModel>>(
        statusCode: 500,
        data: [],
        message: '获取设备列表失败：$e',
        success: false,
      );
    }
  }
  
  /// 获取设备详情
  Future<ApiResponse<DeviceModel>> getDeviceById(String id) async {
    try {
      final response = await _apiProvider.get('${ApiEndpoints.devices}/$id');

      if (response.isOk) {
        final Map<String, dynamic> data = response.body['data'] as Map<String, dynamic>;
        final DeviceModel device = DeviceModel.fromJson(data);

        return ApiResponse<DeviceModel>(
          statusCode: response.statusCode ?? 200,
          data: device,
          message: response.body['message'] as String? ?? '获取设备详情成功',
          success: true,
        );
      } else {
        return ApiResponse<DeviceModel>(
          statusCode: response.statusCode ?? 500,
          data: DeviceModel.empty(),
          message: response.body['message'] as String? ?? '获取设备详情失败',
          success: false,
        );
      }
    } catch (e) {
      return ApiResponse<DeviceModel>(
        statusCode: 500,
        data: DeviceModel.empty(),
        message: '获取设备详情失败：$e',
        success: false,
      );
    }
  }
  
  /// 添加设备
  Future<ApiResponse<DeviceModel>> addDevice(DeviceModel device) async {
    try {
      final response = await _apiProvider.post(
        ApiEndpoints.devices,
        device.toJson(),
      );

      if (response.isOk) {
        final Map<String, dynamic> data = response.body['data'] as Map<String, dynamic>;
        final DeviceModel newDevice = DeviceModel.fromJson(data);

        return ApiResponse<DeviceModel>(
          statusCode: response.statusCode ?? 201,
          data: newDevice,
          message: response.body['message'] as String? ?? '添加设备成功',
          success: true,
        );
      } else {
        return ApiResponse<DeviceModel>(
          statusCode: response.statusCode ?? 500,
          data: DeviceModel.empty(),
          message: response.body['message'] as String? ?? '添加设备失败',
          success: false,
        );
      }
    } catch (e) {
      return ApiResponse<DeviceModel>(
        statusCode: 500,
        data: DeviceModel.empty(),
        message: '添加设备失败：$e',
        success: false,
      );
    }
  }
  
  /// 更新设备
  Future<ApiResponse<DeviceModel>> updateDevice(String id, DeviceModel device) async {
    try {
      final response = await _apiProvider.put(
        '${ApiEndpoints.devices}/$id',
        device.toJson(),
      );

      if (response.isOk) {
        final Map<String, dynamic> data = response.body['data'] as Map<String, dynamic>;
        final DeviceModel updatedDevice = DeviceModel.fromJson(data);

        return ApiResponse<DeviceModel>(
          statusCode: response.statusCode ?? 200,
          data: updatedDevice,
          message: response.body['message'] as String? ?? '更新设备成功',
          success: true,
        );
      } else {
        return ApiResponse<DeviceModel>(
          statusCode: response.statusCode ?? 500,
          data: DeviceModel.empty(),
          message: response.body['message'] as String? ?? '更新设备失败',
          success: false,
        );
      }
    } catch (e) {
      return ApiResponse<DeviceModel>(
        statusCode: 500,
        data: DeviceModel.empty(),
        message: '更新设备失败：$e',
        success: false,
      );
    }
  }
  
  /// 删除设备
  Future<ApiResponse<bool>> deleteDevice(String id) async {
    try {
      final response = await _apiProvider.delete('${ApiEndpoints.devices}/$id');

      if (response.isOk) {
        return ApiResponse<bool>(
          statusCode: response.statusCode ?? 200,
          data: true,
          message: response.body['message'] as String? ?? '删除设备成功',
          success: true,
        );
      } else {
        return ApiResponse<bool>(
          statusCode: response.statusCode ?? 500,
          data: false,
          message: response.body['message'] as String? ?? '删除设备失败',
          success: false,
        );
      }
    } catch (e) {
      return ApiResponse<bool>(
        statusCode: 500,
        data: false,
        message: '删除设备失败：$e',
        success: false,
      );
    }
  }
  
  /// 控制设备
  /// [deviceId] 设备ID
  /// [command] 控制命令
  /// [params] 命令参数
  Future<ApiResponse<Map<String, dynamic>>> controlDevice(
    String deviceId,
    String command, {
    Map<String, dynamic>? params,
  }) async {
    try {
      final Map<String, dynamic> data = {
        'command': command,
        if (params != null) 'params': params,
      };

      final response = await _apiProvider.post(
        '${ApiEndpoints.devices}/$deviceId/control',
        data,
      );

      if (response.isOk) {
        return ApiResponse<Map<String, dynamic>>(
          statusCode: response.statusCode ?? 200,
          data: response.body['data'] as Map<String, dynamic>? ?? {},
          message: response.body['message'] as String? ?? '控制设备成功',
          success: true,
        );
      } else {
        return ApiResponse<Map<String, dynamic>>(
          statusCode: response.statusCode ?? 500,
          data: {},
          message: response.body['message'] as String? ?? '控制设备失败',
          success: false,
        );
      }
    } catch (e) {
      return ApiResponse<Map<String, dynamic>>(
        statusCode: 500,
        data: {},
        message: '控制设备失败：$e',
        success: false,
      );
    }
  }
  
  /// 获取设备数据
  /// [deviceId] 设备ID
  /// [startTime] 开始时间
  /// [endTime] 结束时间
  /// [keys] 需要获取的数据字段列表
  Future<ApiResponse<Map<String, dynamic>>> getDeviceData(
    String deviceId, {
    DateTime? startTime,
    DateTime? endTime,
    List<String>? keys,
  }) async {
    try {
      final Map<String, dynamic> params = {};

      if (startTime != null) {
        params['startTime'] = startTime.toIso8601String();
      }

      if (endTime != null) {
        params['endTime'] = endTime.toIso8601String();
      }

      if (keys != null && keys.isNotEmpty) {
        params['keys'] = keys.join(',');
      }

      final response = await _apiProvider.get(
        '${ApiEndpoints.devices}/$deviceId/data',
        params: params,
      );

      if (response.isOk) {
        return ApiResponse<Map<String, dynamic>>(
          statusCode: response.statusCode ?? 200,
          data: response.body['data'] as Map<String, dynamic>? ?? {},
          message: response.body['message'] as String? ?? '获取设备数据成功',
          success: true,
        );
      } else {
        return ApiResponse<Map<String, dynamic>>(
          statusCode: response.statusCode ?? 500,
          data: {},
          message: response.body['message'] as String? ?? '获取设备数据失败',
          success: false,
        );
      }
    } catch (e) {
      return ApiResponse<Map<String, dynamic>>(
        statusCode: 500,
        data: {},
        message: '获取设备数据失败：$e',
        success: false,
      );
    }
  }
  
  /// 获取设备告警
  /// [deviceId] 设备ID
  /// [startTime] 开始时间
  /// [endTime] 结束时间
  /// [severity] 告警级别（info, warning, error, critical）
  Future<ApiResponse<List<Map<String, dynamic>>>> getDeviceAlarms(
    String deviceId, {
    DateTime? startTime,
    DateTime? endTime,
    String? severity,
  }) async {
    try {
      final Map<String, dynamic> params = {};

      if (startTime != null) {
        params['startTime'] = startTime.toIso8601String();
      }

      if (endTime != null) {
        params['endTime'] = endTime.toIso8601String();
      }

      if (severity != null && severity.isNotEmpty) {
        params['severity'] = severity;
      }

      final response = await _apiProvider.get(
        '${ApiEndpoints.devices}/$deviceId/alarms',
        params: params,
      );

      if (response.isOk) {
        final List<dynamic> data = response.body['data'] as List<dynamic>;
        final List<Map<String, dynamic>> alarms = data
            .map((item) => item as Map<String, dynamic>)
            .toList();

        return ApiResponse<List<Map<String, dynamic>>>(
          statusCode: response.statusCode ?? 200,
          data: alarms,
          message: response.body['message'] as String? ?? '获取设备告警成功',
          success: true,
        );
      } else {
        return ApiResponse<List<Map<String, dynamic>>>(
          statusCode: response.statusCode ?? 500,
          data: [],
          message: response.body['message'] as String? ?? '获取设备告警失败',
          success: false,
        );
      }
    } catch (e) {
      return ApiResponse<List<Map<String, dynamic>>>(
        statusCode: 500,
        data: [],
        message: '获取设备告警失败：$e',
        success: false,
      );
    }
  }
  
  /// 获取设备类型列表
  Future<ApiResponse<List<Map<String, dynamic>>>> getDeviceTypes() async {
    try {
      final response = await _apiProvider.get(ApiEndpoints.deviceTypes);

      if (response.isOk) {
        final List<dynamic> data = response.body['data'] as List<dynamic>;
        final List<Map<String, dynamic>> deviceTypes = data
            .map((item) => item as Map<String, dynamic>)
            .toList();

        return ApiResponse<List<Map<String, dynamic>>>(
          statusCode: response.statusCode ?? 200,
          data: deviceTypes,
          message: response.body['message'] as String? ?? '获取设备类型列表成功',
          success: true,
        );
      } else {
        return ApiResponse<List<Map<String, dynamic>>>(
          statusCode: response.statusCode ?? 500,
          data: [],
          message: response.body['message'] as String? ?? '获取设备类型列表失败',
          success: false,
        );
      }
    } catch (e) {
      return ApiResponse<List<Map<String, dynamic>>>(
        statusCode: 500,
        data: [],
        message: '获取设备类型列表失败：$e',
        success: false,
      );
    }
  }

  /// 获取设备列表
  Future<BaseResponse<List<DeviceModel>>> getDeviceList({
    String? userId,
    int page = 1,
    int limit = 20,
    Map<String, dynamic>? filters,
  }) async {
    // 构建查询参数
    final query = <String, dynamic>{
      'page': page.toString(),
      'limit': limit.toString(),
      if (userId != null) 'user_id': userId,
      ...?filters, // 添加其他筛选条件
    };
    
    // 使用封装好的 getRequest 方法
    return getRequest<List<DeviceModel>>(
      '/devices', // 设备列表API端点
      (json) { // fromJson 函数处理列表数据
        if (json is List) {
          return json.map((item) => DeviceModel.fromJson(item as Map<String, dynamic>? ?? {})).toList();
        } else if (json is Map<String, dynamic> && json.containsKey('items')) {
          final items = json['items'] as List?;
          return items?.map((item) => DeviceModel.fromJson(item as Map<String, dynamic>? ?? {})).toList() ?? [];
        }
        return [];
      },
      query: query,
    );
  }

  /// 获取单个设备信息
  Future<BaseResponse<DeviceModel>> getDeviceById(String deviceId) async {
    return getRequest<DeviceModel>(
      '/devices/$deviceId', // 获取单个设备信息的API端点
      (json) => DeviceModel.fromJson(json as Map<String, dynamic>? ?? {}),
    );
  }

  /// 发送设备控制命令
  Future<BaseResponse<Map<String, dynamic>>> sendDeviceCommand(
    String deviceId,
    String command,
    Map<String, dynamic>? params,
  ) async {
    // 假设命令接口返回命令执行结果 (例如成功/失败及原因)
    return postRequest<Map<String, dynamic>>(
      '/devices/$deviceId/command', // 发送设备命令的API端点
      {
        'command': command,
        'params': params,
      },
      (json) => json as Map<String, dynamic>? ?? {},
    );
  }

  /// 添加新设备
  Future<BaseResponse<DeviceModel>> addDevice(Map<String, dynamic> deviceData) async {
    return postRequest<DeviceModel>(
      '/devices', // 添加设备的API端点
      deviceData,
      (json) => DeviceModel.fromJson(json as Map<String, dynamic>? ?? {}),
    );
  }

  /// 更新设备信息
  Future<BaseResponse<DeviceModel>> updateDevice(String deviceId, Map<String, dynamic> updateData) async {
    // 假设使用 PUT 或 PATCH 更新
    return handleResponse<DeviceModel>(
      () => put('/devices/$deviceId', updateData), // 更新设备信息的API端点
      (json) => DeviceModel.fromJson(json as Map<String, dynamic>? ?? {}),
    );
  }

  /// 删除设备
  Future<BaseResponse<void>> deleteDevice(String deviceId) async {
    // 假设删除成功不返回数据体
    return handleResponse<void>(
      () => delete('/devices/$deviceId'), // 删除设备的API端点
      (_) => null,
    );
  }
} 